package com.xnj.testweb.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.xnj.testweb.admin.service.SysUserService;
import com.xnj.testweb.common.Result;
import com.xnj.testweb.common.annotation.LimitAnnotation;
import com.xnj.testweb.common.annotation.MyLogAnnotation;
import com.xnj.testweb.common.annotation.NoLoginCheck;
import com.xnj.testweb.core.entry.SysUser;
import com.xnj.testweb.core.param.AddUserParam;
import com.xnj.testweb.core.param.LogInParam;
import com.xnj.testweb.core.param.PageUserParam;
import com.xnj.testweb.core.param.UpdatePasswordParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yujie
 * @data 2025/4/14 13:47
 */
@Api(tags = "系统管理")
@RestController
@RequestMapping("/sysUser")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

//    @Autowired
//    private LoginLogService loginLogService;

    @NoLoginCheck
    @ApiOperation(value = "登录", notes = "登录")
    @PostMapping("/login")
    public Result<SysUser> login(@RequestBody LogInParam logInParam) throws Exception {
        SysUser sysUser = sysUserService.userLogin(logInParam);
        StpUtil.login(sysUser.getId());

//        // 获取 ip 地址 记录登录日志
//        String ipAddr = IpUtils.getIpAddr();
//        LoginLog loginLog = new LoginLog();
//        loginLog.setUserName(logInParam.getUserName());
//        loginLog.setLoginIp(ipAddr);
//        loginLogService.insertLoginLog(loginLog);
        return Result.success(sysUser, "登录成功");
    }

    @MyLogAnnotation(management = "重置密码", moduleName = "系统管理")
    @ApiOperation(value = "重置密码", notes = "重置密码")
    @GetMapping("/resetPassword")
    public Result resetPassword(@RequestParam @ApiParam("用户名") String userName) throws Exception {
        sysUserService.resetPassword(userName);
        return Result.success(null, "密码已重置");
    }

    @MyLogAnnotation(management = "修改密码", moduleName = "系统管理")
    @ApiOperation(value = "修改密码", notes = "修改密码")
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody UpdatePasswordParam param) throws Exception {
        sysUserService.updatePassword(param);
        return Result.success(null, "密码已修改, 请重新登录");
    }


    @ApiOperation(value = "退出登录", notes = "退出登录")
    @GetMapping("/quitLogin")
    public Result quitLogin(@RequestParam @ApiParam("登录用户id") Integer userId) throws Exception {
        StpUtil.logout(userId);
        return Result.success(null, "账户已退出登录");
    }

    @LimitAnnotation(userLimit = "user.add")
    @MyLogAnnotation(management = "添加用户", moduleName = "系统管理")
    @ApiOperation(value = "添加新用户", notes = "添加新用户")
    @PostMapping("/register")
    public Result register(@RequestBody AddUserParam addUserParam) throws Exception {
        sysUserService.userRegister(addUserParam);
        return Result.success(null, "添加成功");
    }

    @MyLogAnnotation(management = "更新数据", moduleName = "系统管理")
    @ApiOperation(value = "修改用户信息", notes = "修改用户信息")
    @PostMapping("/update")
    public Result update(@RequestBody SysUser SysUser) {
        SysUser user = sysUserService.update(SysUser);
        return Result.success(user, "修改成功");
    }

    @MyLogAnnotation(management = "删除数据", moduleName = "系统管理")
    @ApiOperation(value = "删除用户信息", notes = "修改用户信息")
    @GetMapping("/delete")
    public Result delete(@RequestParam @ApiParam("用户id") Integer id) {
        sysUserService.deleteUserById(id);
        return Result.success(null, "删除成功");
    }

    @LimitAnnotation(userLimit = "user.get")
    @MyLogAnnotation(management = "查询详细", moduleName = "系统管理")
    @ApiOperation(value = "根据id查询用户信息", notes = "根据id查询用户信息")
    @GetMapping("/selectById")
    public Result selectById(@RequestParam @ApiParam("登录用户id") Integer id) {
        SysUser user = sysUserService.selectById(id);
        return Result.success(user);
    }

    @MyLogAnnotation(management = "分页查询", moduleName = "系统管理")
    @ApiOperation(value = "分页查询用户信息", notes = "分页查询用户信息")
    @GetMapping("/page")
    public Result<SysUser> page(PageUserParam param) {
        Page<SysUser> list = sysUserService.pageSysUserList(param);
        return Result.success(list);
    }

    @NoLoginCheck
    @GetMapping("/pdf")
    public ResponseEntity<Resource> pdf() {
        // 示例数据
        List<DataObject> dataList = List.of(
                new DataObject("YN2024/00440201", "隔板货架区", new Date()),
                new DataObject("YN2024/00440202", "料箱存储区矮货架", new Date()),
                new DataObject("YN2024/00440203", "料箱存储区高货架", new Date())
        );

        // 生成PDF文件
        generatePdf("D:\\downloadAll\\pdf\\output.pdf", dataList);

        String filePath = "D:\\downloadAll\\pdf\\output.pdf";

//        File file = new File(filePath);
//
//        // 检查文件是否存在
//        if (!file.exists()) {
//            throw new RuntimeException("文件不存在: " + filePath);
//        }
//
//        try {
//            // 读取文件内容
//            FileInputStream fileInputStream = new FileInputStream(file);
//
//            // 设置响应头
//            HttpHeaders headers = new HttpHeaders();
//            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=output.pdf"); // 指定文件名
//            headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE); // 指定文件类型为 PDF
//
//            // 返回文件流
//            return ResponseEntity.ok()
//                    .headers(headers)
//                    .contentLength(file.length())
//                    .body(new InputStreamResource(fileInputStream));
//        } catch (FileNotFoundException e) {
//            throw new RuntimeException("文件读取失败: " + e.getMessage());
//        }

//        File file = new File(filePath);
//
//        // 检查文件是否存在
//        if (!file.exists()) {
//            throw new RuntimeException("文件不存在: " + filePath);
//        }
//
//        // 设置响应头
//        HttpHeaders headers = new HttpHeaders();
//        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=output.pdf"); // 指定文件名
//        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE); // 指定文件类型为 PDF
//
//        // 创建 StreamingResponseBody
//        StreamingResponseBody responseBody = outputStream -> {
//            try (InputStream inputStream = new FileInputStream(file)) {
//                byte[] buffer = new byte[1024];
//                int bytesRead;
//                while ((bytesRead = inputStream.read(buffer)) != -1) {
//                    outputStream.write(buffer, 0, bytesRead);
//                }
//                outputStream.flush();
//            } catch (IOException e) {
//                throw new RuntimeException("文件读取失败: " + e.getMessage());
//            }
//        };
//
//        // 返回文件流
//        return ResponseEntity.ok()
//                .headers(headers)
//                .contentLength(file.length())
//                .body(responseBody);


        File file = new File(filePath);

        // 检查文件是否存在
        if (!file.exists()) {
            throw new RuntimeException("文件不存在: " + filePath);
        }

        // 创建 Resource 对象
        Resource resource = new FileSystemResource(file);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=output.pdf"); // 指定文件名
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE); // 指定文件类型为 PDF

        // 返回文件 Resource
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .body(resource);

    }


    @ApiOperation(value = "角色下拉列表", notes = "角色下拉列表")
    @GetMapping("/roleList")
    public Result roleList() {
        Map<String, String> map = new HashMap<>();
        map.put("admin", "管理员");
        map.put("manage", "业务主管");
        map.put("clerk", "业务专职");
        return Result.success(map);
    }


    // 定义中文字体
    private static Font chineseFont;

    static {
        try {
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            chineseFont = new Font(bf, 12, Font.NORMAL);
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }
    }

    public static void generatePdf(String filePath, List<DataObject> dataList) {
        Document document = new Document(PageSize.A4);
        try {
            PdfWriter.getInstance(document, new FileOutputStream(filePath));
            document.open();

            // 创建表格，列数为3
            PdfPTable table = new PdfPTable(3);
            table.setWidthPercentage(100);

            // 添加表头
            addTableHeader(table);

            // 添加数据行
            for (DataObject data : dataList) {
                addRow(table, data);
            }

            document.add(table);
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }

    private static void addTableHeader(PdfPTable table) {
        PdfPCell cell = new PdfPCell(new Phrase("样品编号", chineseFont));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("货区", chineseFont));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("时间", chineseFont));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
    }

    private static void addRow(PdfPTable table, DataObject data) {
        table.addCell(new Phrase(data.getName(), chineseFont));
        table.addCell(new Phrase(data.getAge(), chineseFont));
        table.addCell(new Phrase(formatDateToString(data.getAddress()), chineseFont));
    }

    public static void main(String[] args) {
        // 示例数据
        List<DataObject> dataList = List.of(
                new DataObject("YN2024/00440201", "隔板货架区", new Date()),
                new DataObject("YN2024/00440202", "料箱存储区矮货架", new Date()),
                new DataObject("YN2024/00440203", "料箱存储区高货架", new Date())
        );

        // 生成PDF文件
        generatePdf("D:\\downloadAll\\pdf\\output.pdf", dataList);
    }

    public static String formatDateToString(Date date) {
        // 定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 格式化 Date 对象
        return sdf.format(date);
    }
}

